import React, { PureComponent } from 'react'
import { history } from '@umijs/max'
import {
  Select, Button, message, Popconfirm, Modal, Form, TreeSelect, Input, DatePicker, Tooltip, Spin,
} from 'antd'
import list2tree from 'list2tree'
import KeepAlive from 'react-activation'
import {
  ProTable, ProTableOperate, ProTableOptions, InputSearch, Logger, ProTree, HufuTreeTitle, searchTreeListByName, OSSyncComponentModal,
} from '@/components'
import {
  getSummary, publish, unPublish, deleteOnline, reRun, deleteDir, upsetDir, getDirList, onlineTaskLog,
} from './api'
import styles from './index.less'

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'dirName',
  },
})
const { Item } = Form
const { OperateItem } = ProTableOperate
const { Option } = Select
const { RangePicker } = DatePicker

const status = [
  {
    key: 1,
    value: '待发布',
  },
  {
    key: 2,
    value: '已发布',
  },
  {
    key: 3,
    value: '未运行',
  },
  {
    key: 4,
    value: '运行中',
  },
  {
    key: 6,
    value: '失败',
  },
]

const statusObj = {
  1: {
    key: 1,
    value: '待发布',
    icon: 'icon-daiban',
    color: '#0084FF',
  },
  2: {
    key: 2,
    value: '已发布',
    icon: 'icon-yifabu',
    color: '#43A047',
  },
  3: {
    key: 3,
    value: '未运行',
    icon: 'icon-weiyunhang',
    color: '#0084FF',
  },
  4: {
    key: 4,
    value: '运行中',
    icon: 'icon-yunhangzhong_1',
    color: '#0084FF',
  },
  6: {
    key: 6,
    value: '失败',
    icon: 'icon-shibai1',
    color: '#EF5350',
  },
}

class SersyncCenter extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      statistic: null,
      query: {},
      taskName: '',
      taskStatus: '',
      treeDataNew: [],
      selectedKeys: ['0'],
      osSyncVisible: false,
      osSynclabel: '',
      osSyncjobid: '',
      columns: [
        {
          title: '任务名称', dataIndex: 'taskName', key: 'taskName',
        },
        {
          title: '源端', dataIndex: 'source', key: 'source',
        },
        {
          title: '目标端', dataIndex: 'target', key: 'target',
        },
        {
          title: (
            <span>
              发布状态
              <Tooltip
                placement="top"
                title={
                  <div>
                    <p>任务是否发布状态</p>
                  </div>
                }
              >
                <i style={{ color: 'rgb(0, 132, 255)' }} className="iconfont icon-yiwentishi" />
              </Tooltip>
            </span>
          ),
          dataIndex: 'taskStatus',
          key: 'taskStatus',
          render: (text, record) => <span> <i style={{ color: statusObj[text] && statusObj[text].color }} className={`iconfont ${statusObj[text] && statusObj[text].icon}`} /> {statusObj[text] && statusObj[text].value}</span>,
        },
        {
          title: (
            <span>
              运行状态
              <Tooltip
                placement="top"
                title={
                  <div>
                    <p>任务是否运行，或任务最后一次的运行状态</p>
                  </div>
                }
              >
                <i style={{ color: 'rgb(0, 132, 255)' }} className="iconfont icon-yiwentishi" />
              </Tooltip>
            </span>
          ),
          dataIndex: 'taskRunStatus',
          key: 'taskRunStatus',
          render: (text, record) => <span> <i style={{ color: statusObj[text] && statusObj[text].color }} className={`iconfont ${statusObj[text] && statusObj[text].icon}`} /> {statusObj[text] && statusObj[text].value}</span>,
        },
        {
          title: '开始时间', dataIndex: 'startTime', key: 'startTime',
        },
        {
          title: '结束时间', dataIndex: 'endTime', key: 'endTime',
        },
        {
          title: '创建人', dataIndex: 'creator', key: 'creator',
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          fixed: 'right',
          width: 200,
          render: (text, record) => {
            const taskStatus = Number(record.taskStatus)
            return (
              <ProTableOptions>
                <span onClick={() => {
                  history.push(`/dataIntegrate/sersync-detail?id=${record.id}`)
                }}
                >查看
                </span>
                {taskStatus !== 2 ? (
                  <span onClick={() => {
                    history.push(`/dataIntegrate/sersync-create?id=${record.id}`)
                  }}
                  >编辑
                  </span>
                ) : null}
                {taskStatus === 1 ? (
                  <span
                    onClick={() => {
                      this.publish(record.id)
                    }}
                  >发布
                  </span>
                ) : null}
                {taskStatus !== 1 ? (
                  <span onClick={() => {
                    this.unPublish(record.id)
                  }}
                  >下线
                  </span>
                ) : null}
                {taskStatus !== 2 ? (
                  <Popconfirm title="确定要删除吗？" onConfirm={() => { this.deleteOnline(record.id) }} okText="是" cancelText="否">
                    <span>
                      删除
                    </span>
                  </Popconfirm>
                ) : null}
                {taskStatus !== 1 ? (
                  <span onClick={() => {
                    this.onlineTaskLog(record.recordId)
                  }}
                  >查看日志
                  </span>
                ) : null}
                {process.env.APP_ENV === 'os' ? (
                  <span onClick={() => { this.onOSSync(record) }}>
                    同步
                  </span>
                ) : null}
              </ProTableOptions>
            )
          },
        },
      ],
      pageLoading: false,
      tableLoading: false,
    }
    this.tableRef = React.createRef()
    this.fileForm = React.createRef()
    this.logger = React.createRef()
  }

  componentDidMount() {
    this.getSummary()
    this.getDirList()
  }

  onOSSync = (record) => {
    this.setState({
      osSyncVisible: true,
      osSyncjobid: record.id,
      osSynclabel: record.taskName,
    })
  }

  getSummary = () => {
    getSummary().then((data) => {
      this.setState({
        statistic: data,
      })
    })
  }

  publish = (id) => {
    const {
      taskName, taskStatus, selectedKeys, taskRunStatus, startTime, endTime,
    } = this.state
    this.setState({
      tableLoading: true,
    })
    publish({ id }).then((res) => {
      this.setState({
        tableLoading: false,
      })
      if (res.status === 200) {
        this.getSummary()
        this.setState({
          query: {
            taskName: taskName || '',
            taskStatus: taskStatus || '',
            dirId: selectedKeys[0] || 0,
            taskRunStatus: taskRunStatus || '',
            startTime: startTime || '',
            endTime: endTime || '',
          },
        })
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
    })
  }

  unPublish = (id) => {
    const {
      taskName, taskStatus, selectedKeys, taskRunStatus, startTime, endTime,
    } = this.state
    this.setState({ tableLoading: true })
    unPublish({ id }).then((res) => {
      this.setState({ tableLoading: false })
      if (res.status === 200) {
        this.getSummary()
        this.setState({
          query: {
            taskName: taskName || '',
            taskStatus: taskStatus || '',
            dirId: selectedKeys[0] || 0,
            taskRunStatus: taskRunStatus || '',
            startTime: startTime || '',
            endTime: endTime || '',
          },
        })
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
    })
  }

  deleteOnline = (id) => {
    const {
      taskName, taskStatus, selectedKeys, taskRunStatus, startTime, endTime,
    } = this.state
    this.setState({ tableLoading: true })
    deleteOnline({ id }).then((res) => {
      this.setState({ tableLoading: false })
      if (res.status === 200) {
        this.getSummary()
        this.setState({
          query: {
            taskName: taskName || '',
            taskStatus: taskStatus || '',
            dirId: selectedKeys[0] || 0,
            taskRunStatus: taskRunStatus || '',
            startTime: startTime || '',
            endTime: endTime || '',
          },
        })
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
    })
  }

  // reRun = (id) => {
  //   const { taskName, taskStatus, selectedKeys } = this.state
  //   reRun({ id }).then((res) => {
  //     if (res.status === 200) {
  //       this.setState({
  //         query: {
  //           taskName: taskName || '',
  //           taskStatus: taskStatus || '',
  //           dirId: selectedKeys[0] || 0,
  //         },
  //       })
  //       message.success(res.msg)
  //     } else {
  //       message.error(res.msg)
  //     }
  //   })
  // }

  onlineTaskLog = (recordId) => {
    this.setState({
      log: [],
      pageLoading: true,
    })
    this.logger.current.iconUpFn()
    onlineTaskLog({
      recordId,
      offset: 0,
    }).then((res) => {
      this.setState({
        pageLoading: false,
      })
      if (res?.status === 200) {
        if (res?.data) {
          this.setState({
            log: res?.data?.logContent || [],
          })
        }
        message.success(res?.msg || '操作成功')
      } else {
        message.error(res?.msg || '服务端错误')
      }
    })
  }

  renderTreeNodes = (data) => {
    const tempArr = []
    data.map((item) => {
      const {
        title, children, layerNum, ...restProps
      } = item
      const tempObj = {
        icon: this.defaultIconFun,
        ...restProps,
      }
      tempObj.title = (
        <HufuTreeTitle
          title={title}
          key={item.id}
          icon
          operations={item.id === '0' ? [
            <a
              key={`new${item.id}`}
              onClick={() => this.showModal(item.id)}
            >
              新建目录
            </a>,
          ] : [
            <a
              key={`new${item.id}`}
              onClick={() => this.showModal(item.id)}
            >
              新建目录
            </a>,
            <a
              key={`edit${item.id}`}
              onClick={() => this.onEditClick(item)}
            >
              编辑目录
            </a>,
            <Popconfirm
              title="你确定要删除这个目录吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => this.deleteTheme(item)}
              key={`delPop${item.id}`}
            >
              <a
                key={`del${item.id}`}
              >
                删除
              </a>
            </Popconfirm>,
          ]}
        />
      )

      if (item.children) {
        tempObj.children = this.renderTreeNodes(item.children)
      }
      tempArr.push(tempObj)
    })
    return tempArr
  }

  // 打开新建目录弹窗
  showFilesModal = (id) => {
    this.fileForm.current?.resetFields()
    this.setState({
      isShowFiles: true,
      modifyId: null,
    }, () => {
      if (id) {
        this.fileForm.current.setFieldsValue({ pid: id })
      }
    })
  }

  getDirList = () => {
    getDirList().then((res) => {
      this.setState({
        treeData: res.data,
        treeDataNew: getNavTreeDataFunc(res.data || []),
      })
    }, (error) => {
    })
  }

  upsetDir = () => {
    this.fileForm.current.validateFields().then(values => {
      upsetDir({
        ...values,
        id: this.state.modifyId,
      }).then((res) => {
        if (res.status === 200) {
          message.success(res.msg)
          this.getDirList()
          this.setState({
            isShowFiles: false,
          })
        } else {
          message.error(res.msg)
        }
      }, (error) => {
      })
    })
  }

  showModal = (id) => {
    this.fileForm.current?.resetFields()
    this.setState({
      isShowFiles: true,
      modifyId: null,
    }, () => {
      this.fileForm.current.setFieldsValue({
        pid: id,
      })
    })
  }

  onEditClick = (item) => {
    this.setState({
      isShowFiles: true,
      modifyId: item.id,
    }, () => {
      this.fileForm.current.setFieldsValue({
        pid: item.pid,
        dirName: item.title,
      })
    })
  }

  defaultIconFun = props => {
    const { selectedKeys } = this.state
    if (selectedKeys && selectedKeys[0] === props.data.key) {
      return props.expanded ? <i className="iconfont-colour2 icon-wenjianjia-dakaihover" /> : <i className="iconfont-colour2 icon-wenjianjia-morenhover" />
    }
    return props.expanded ? <i className="iconfont-colour2 icon-wenjianjia-dakai" /> : <i className="iconfont-colour2 icon-wenjianjia-moren" />
  }

  // 删除主题
  deleteTheme = (data) => {
    deleteDir({ id: data.id }).then(
      (res) => {
        this.getDirList()
      },
      (error) => {
        console.log(error)
      },
    )
  }

  onSelect = (selectedKeys) => {
    const {
      taskName, taskStatus, taskRunStatus, startTime, endTime,
    } = this.state
    this.setState({
      selectedKeys,
      query: {
        taskName: taskName || '',
        taskStatus: taskStatus || '',
        dirId: selectedKeys[0] || 0,
        taskRunStatus: taskRunStatus || '',
        startTime: startTime || '',
        endTime: endTime || '',
      },
    })
  }

  render() {
    const {
      statistic, query, taskName, taskStatus, treeDataNew, selectedKeys, treeData, taskRunStatus, startTime, endTime, time, pageLoading,
      tableLoading, osSyncVisible, osSyncjobid, osSynclabel,
    } = this.state
    return (
      <Spin spinning={pageLoading} wrapperClassName={styles.spin_wrap}>
        <div className={`${styles.page_content_with_breadcrumb} ${styles.page_content_tabs_height}`}>
          <div className={styles.data_show}>
            <div className={styles.item}>
              <div className={styles.text_overflow_single}><span className={styles.column}>运行中</span> <span className={styles.count}>{statistic && statistic.running}</span></div>
              <i className="iconfont-colour2 icon-yunhangzhong" />
            </div>
            <div className={styles.item}>
              <div className={styles.text_overflow_single}><span className={styles.column}>待发布</span> <span className={styles.count}>{statistic && statistic.toBeReleased}</span></div>
              <i className="iconfont-colour2 icon-yunhangzhong" />
            </div>
            <div className={styles.item}>
              <div className={styles.text_overflow_single}><span className={styles.column}>失败</span> <span className={styles.count}>{statistic && statistic.fail}</span></div>
              <i className="iconfont-colour2 icon-shibai_1" />
            </div>
          </div>
          <div className={`${styles.page_content_column} ${styles.page_content_column_ro}`}>
            <div className={styles.data_dev_left}>
              <ProTree
                showLine
                showSearch
                showTitle
                operations={[
                  <i
                    key="1"
                    className="iconfont icon-xinjianwenjianjia"
                    title="新建目录"
                    onClick={() => this.showFilesModal()}
                  />,
                ]}
                treeData={treeDataNew}
                renderTreeNodes={this.renderTreeNodes}
                selectedKeys={selectedKeys}
                onSelect={this.onSelect}
                ref={(dev) => (this.tree = dev)}
                search={(name) => {
                  const searchTree = searchTreeListByName(
                    name,
                    treeData,
                    'dirName',
                  )
                  const treeDataNews = getNavTreeDataFunc(
                    searchTree.result,
                  )
                  this.setState(
                    {
                      treeDataNew: treeDataNews,
                    },
                    () => {
                      this.tree.onExpand(searchTree.fatchIds)
                    },
                  )
                }}
              />
            </div>
            <div className={`${styles.page_content_right} ${styles.page_content_right_flex}`}>
              <div className={styles.sersync}>
                <ProTableOperate style={{ marginBottom: 12 }}>
                  <OperateItem>
                    <span>运行状态</span>
                    <Select
                      allowClear
                      value={taskRunStatus}
                      placeholder="请选择任务状态"
                      onChange={(value) => {
                        this.tableRef?.current?.resetPageNum()
                        this.setState({
                          taskRunStatus: value,
                          query: {
                            taskName: taskName || '',
                            taskStatus: taskStatus || '',
                            dirId: selectedKeys[0] || 0,
                            taskRunStatus: value || '',
                            startTime: startTime || '',
                            endTime: endTime || '',
                          },
                        })
                      }}
                    >
                      <Option value={status[2].key} key={status[2].key}>{status[2].value}</Option>
                      <Option value={status[3].key} key={status[3].key}>{status[3].value}</Option>
                      <Option value={status[4].key} key={status[4].key}>{status[4].value}</Option>
                    </Select>
                  </OperateItem>
                  <OperateItem>
                    <span>发布状态</span>
                    <Select
                      allowClear
                      value={taskStatus}
                      placeholder="请选择任务状态"
                      onChange={(value) => {
                        this.tableRef?.current?.resetPageNum()
                        this.setState({
                          taskStatus: value,
                          query: {
                            taskName: taskName || '',
                            taskStatus: value || '',
                            dirId: selectedKeys[0] || 0,
                            taskRunStatus: taskRunStatus || '',
                            startTime: startTime || '',
                            endTime: endTime || '',
                          },
                        })
                      }}
                    >
                      <Option value={status[0].key} key={status[0].key}>{status[0].value}</Option>
                      <Option value={status[1].key} key={status[1].key}>{status[1].value}</Option>
                    </Select>
                  </OperateItem>
                  <OperateItem>
                    <span>任务时间</span>
                    <RangePicker
                      value={time}
                      onChange={(times) => {
                        this.tableRef?.current?.resetPageNum()
                        this.setState({
                          time: times,
                          startTime: times && times[0] ? times[0].format('YYYY-MM-DD') : '',
                          endTime: times && times[1] ? times[1].format('YYYY-MM-DD') : '',
                          query: {
                            taskName: taskName || '',
                            taskStatus: taskStatus || '',
                            dirId: selectedKeys[0] || 0,
                            taskRunStatus: taskRunStatus || '',
                            startTime: times && times[0] ? times[0].format('YYYY-MM-DD') : '',
                            endTime: times && times[1] ? times[1].format('YYYY-MM-DD') : '',
                          },
                        })
                      }}
                    />
                  </OperateItem>
                  <OperateItem align="left">
                    <span />
                    <InputSearch
                      placeholder="请输入任务名称进行搜索"
                      value={taskName}
                      onChange={(e) => {
                        this.setState({
                          taskName: e.target.value,
                        })
                      }}
                      onSearch={(e) => {
                        this.tableRef?.current?.resetPageNum()
                        this.setState({
                          query: {
                            taskName: e || '',
                            taskStatus: taskStatus || '',
                            dirId: selectedKeys[0] || 0,
                            taskRunStatus: taskRunStatus || '',
                            startTime: startTime || '',
                            endTime: endTime || '',
                          },
                        })
                      }}
                    />
                  </OperateItem>
                  <OperateItem itemType="btn">
                    <Button type="primary" onClick={() => { history.push(`/dataIntegrate/sersync-create?dirId=${selectedKeys[0] || 0}`) }}>新建实时任务</Button>
                  </OperateItem>
                </ProTableOperate>
                <ProTable
                  loading={tableLoading}
                  ref={this.tableRef}
                  rowKey="id"
                  columns={this.state.columns}
                  query={query}
                  border={false}
                  scroll={{
                    x: 2000,
                  }}
                  url="/api/v1/integration/online/page"
                />
              </div>
              <Logger
                list={this.state.log || []}
                ref={this.logger}
              />
            </div>
          </div>
          <Modal
            title={this.state.modifyId ? '修改目录' : '新建目录'}
            visible={this.state.isShowFiles}
            confirmLoading={this.state.navListSpinning}
            cancelText="取消"
            okText="保存"
            onOk={this.upsetDir}
            onCancel={() => {
              this.setState({
                isShowFiles: false,
                modifyId: null,
              })
            }}
            maskClosable={false}
          >
            <div className={styles.file_box}>
              <Form
                ref={this.fileForm}
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
                autoComplete="off"
              >
                <Item
                  label="目录名称"
                  name="dirName"
                  rules={[
                    { required: true, message: '请输入目录名称' },
                  ]}
                >
                  <Input placeholder="请输入目录名称" />
                </Item>
                <Item
                  label="父级目录"
                  name="pid"
                >
                  <TreeSelect
                    allowClear
                    showSearch
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    // dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    treeData={getNavTreeDataFunc(treeData || [])}
                    placeholder="请选择父级目录"
                    treeDefaultExpandAll
                    filterTreeNode={(input, treeNode) => treeNode.name.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    fieldNames={{
                      label: 'dirName', value: 'id', children: 'children',
                    }}
                  />
                </Item>
              </Form>
            </div>
          </Modal>
          <OSSyncComponentModal
            visible={osSyncVisible}
            onClose={() => this.setState({ osSyncVisible: false })}
            jobtype="2"
            jobid={osSyncjobid}
            label={osSynclabel}
          />
        </div>
      </Spin>
    )
  }
}

export default class Sersync extends PureComponent {
  render() {
    return (
      <KeepAlive
        saveScrollPosition="screen"
        when={() => {
          if (history.location.pathname === '/dataIntegrate/sersync-detail') {
            return true
          }
          return false
        }}
        cacheKey="Sersync_ID"
      ><SersyncCenter />
      </KeepAlive>
    )
  }
}
